<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/10
 * Time: 11:58
 */

namespace App\Services;

use App\Goods;
use App\GoodsFiles;
use App\Reagent;
use DB;
use App\Lib\Util\QueryPager;
use App\ServiceFiles;

class FileService
{
    public function getFiles(Array $input, $paging = true)
    {
        $query = new ServiceFiles();

        if(!empty($input['name'])){
            $query = $query->where('name','like','%'.$input['name'].'%');
        }

        $pager = new QueryPager($query);

        $pager->setRefectionMethodField('getFullPath');

        return $paging ? $pager->doPaginate($input, 'sort_order') :
            $pager->queryWithoutPaginate($input, 'sort_order');
    }

    public function getAllFile()
    {
        return ServiceFiles::get();
    }

    public function saveFile(Array $input)
    {

        ServiceFiles::insert($input);
    }

    //删除文件
    public function delFile(Array $input)
    {
        DB::transaction(function () use ($input) {
            $info     = ServiceFiles::where('id', $input['id'])->first();
            $fullPath = 'storage/upload/' . $info->file_id;
            unlink($fullPath);
            ServiceFiles::where('id', $input['id'])->delete();
        });
    }

    //通过商品获取关联文件
    public function getFileDetail($goodsId)
    {
        return ServiceFiles::select('service_files.file_id', 'service_files.name')->where('goods_files.goods_id', $goodsId)
            ->leftJoin('goods_files', 'goods_files.file_id', '=', 'service_files.id')
            ->get();
    }

    //查询文件和商品是否关联
    public function isGoodsFile($file_id)
    {
        return GoodsFiles::where('file_id', $file_id)->first();
    }

    //查询试剂管理是否关联
    public function isReagentFile($file_id)
    {
        return Reagent::where('file_id', $file_id)->first();
    }

    //获取试剂管理信息
    public function getReagentInfo(Array $input)
    {
        $query = new Reagent();
        $pager = new QueryPager($query);
        $pager->setRefectionMethodField('serviceFile');
        $pager->setRefectionMethodField('getFullPath');
        return $pager->doPaginate($input, 'id');
    }
    //获取试剂管理信息不分页
    public function getReagentInfoNoPage()
    {
        $query = new Reagent();
        $pager = new QueryPager($query);
        $pager->setRefectionMethodField('serviceFile');
        $pager->setRefectionMethodField('getFullPath');
        return $pager->queryWithoutPaginate([], 'id');
    }


    //修改试剂管理信息
    public function editReagent(Array $input)
    {
        Reagent::where('id', $input['id'])->update([
            'file_id'     => $input['file_id'],
            'reagent_img' => $input['reagent_img'],
        ]);
    }
}